package com.qingfeng.client.api;

import com.alibaba.fastjson.JSONObject;
import com.qingfeng.client.bean.Buyer;
import com.qingfeng.client.dao.BuyerMapper;
import com.qingfeng.coupon.service.CouponService;
import com.qingfeng.util.ApiMsg;
import com.qingfeng.util.OkhttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author zhangyuefei
 * @version 1.0
 * @date 2020/1/3 9:13 上午@Controller
 */
@Api(tags = "首页")
@Controller
@RequestMapping("/")
public class AppIndexApi extends BaseV1Api {

    @Value("${wx.appid}")
    private String APPID;

    @Value("${wx.secret}")
    private String SECRET;

    @Resource
    private BuyerMapper buyerDAO;

    @Autowired
    private CouponService couponService;

    @ApiOperation("进入首页")
    @GetMapping("/")
    public String getIndex(){
        return "index";
    }



    @ApiOperation("微信登陆")
    @RequestMapping(value = "/newLogin")
    @ResponseBody
    public ApiMsg newLogin(@RequestBody JSONObject json) throws InterruptedException {
        String code = json.getString("code");
        Buyer bean = (Buyer) request.getSession().getAttribute("buyerBean");
        //判断是否在刷新页面
        if(bean != null){
            //返回页面
            ApiMsg apiMsg= success("登录成功");
            apiMsg.setResult(1);
            return apiMsg;
        }
        System.out.println("appid and secret "+ APPID+":"+SECRET);
        //跳转路径
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret=" + SECRET +
                "&code=" + code + "&grant_type=authorization_code";
        String openId;
        String result;
        //昵称
        String nickname;
        //头像
        String headimgurl;
        //token
        String access_token;
        //是否可以获取到openId
        try {
            result = OkhttpUtil.get(url);
            System.out.println("获取openId 和 token"+result);
            openId = JSONObject.parseObject(result).getString("openid");
            access_token = JSONObject.parseObject(result).getString("access_token");
        } catch (Exception e) {
            e.printStackTrace();
//            return error("获取openId失败");
            return error("获取openId失败");
        }

        String getUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openId + "&lang=zh_CN";
        try {
            result = OkhttpUtil.get(getUrl);
            System.out.println("获取用户信息："+result);
            nickname = JSONObject.parseObject(result).getString("nickname");
            headimgurl = JSONObject.parseObject(result).getString("headimgurl");
            openId = JSONObject.parseObject(result).getString("openid");
        } catch (Exception e) {
            e.printStackTrace();
            return error("获取openId失败");
//            return "error";
        }
        if (openId == null) {
            return error("获取openId失败");
//            return "error";
        }
        //将openId保存在session中
        request.getSession().setAttribute("openId", openId);
        //查询用户是否有openId
        Buyer buyerBean = buyerDAO.getByOpenId(openId);
        System.out.println("get db userInfo");
        System.out.println(buyerBean);
        if (buyerBean != null) {
            //自动登录
            buyerBean.setPortrait(headimgurl);
            buyerDAO.updateById(buyerBean);
            request.getSession().setAttribute("buyerBean", buyerBean);
        } else {
            Buyer buyer = new Buyer();
            buyer.setOpenId(openId);
            buyer.setName(nickname);
            buyer.setPassword(null);
            buyer.setCreateTime(System.currentTimeMillis()/1000);
            buyer.setPortrait(headimgurl);
            System.out.println(buyer);
            int flag = buyerDAO.insert(buyer);
            request.getSession().setAttribute("buyerBean", buyer);
            // 自动领取新人优惠券
            couponService.receiveRegisterCouponTemplate(buyer.getId());
        }
        //踢掉其他地方的登录
        return success();
    }
}
